package com.water.camera.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.water.camera.App;
import com.water.camera.adapter.BatchAdapter;
import com.water.camera.bean.MediaData;
import com.water.camera.databinding.ActivityDmBatchPhotoBinding;
import com.water.camera.util.Read;
import com.water.camera.util.Utils;

import java.util.ArrayList;
import java.util.List;

public class BatchPhotoAct extends BaseActivity {

    ActivityDmBatchPhotoBinding binding;
    BatchAdapter adapter;
    int page = 0;
    boolean working = false;
    int from;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDmBatchPhotoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.includeToolbar.ivBack.setOnClickListener(v -> finish());
        binding.includeToolbar.tvTitleName.setText("全部照片");
        from = getIntent().getIntExtra("from", 0);
        if (from == 1) {
            binding.btnAdd.setText("开始拼图");
        }

        GridLayoutManager manager = new GridLayoutManager(this, 3);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) == 0) {
                    return 3;
                }
                return 1;
            }
        });
        binding.rvAlbum.setLayoutManager(manager);
        binding.rvAlbum.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (manager.findLastVisibleItemPosition() < adapter.getItemCount() - 6) {
                        loadImages(++page);
                    }
                }
            }
        });
        adapter = new BatchAdapter(this);
        binding.rvAlbum.setAdapter(adapter);

        binding.btnAdd.setEnabled(false);
        binding.btnAdd.setOnClickListener(v -> {
            if (from == 1) {
                Intent i = new Intent();
                i.putParcelableArrayListExtra("img", adapter.getSelect());
                i.putExtra("position", getIntent().getIntExtra("position", -1));
                setResult(RESULT_OK, i);
                finish();
            } else {
                Intent i = new Intent(this, BatchPreviewAct.class);
                i.putParcelableArrayListExtra("img", adapter.getSelect());
                startActivityForResult(i, 11);
            }
        });

        loadImages(page);
    }

    private void loadImages(int page) {
        if (working) {
            return;
        }
        working = true;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    List<MediaData> list = new Read().loadImageData(App.getApp(), page);
                    if (list == null || list.isEmpty()) {
                        if (page == 0) {
                            h.post(() -> adapter.setData(null, 0));
                        }
                        return;
                    }
                    long time = list.get(0).getAddTime();
                    int j = 0;
                    SparseArray<ArrayList<MediaData>> array = new SparseArray();
                    ArrayList<MediaData> l = new ArrayList();
                    l.add(list.get(0));
                    array.put(0, l);
                    for (int i = 1; i < list.size(); i++) {
                        MediaData m = list.get(i);
                        if (Utils.isSameDate(time, m.getAddTime())) {
                            l.add(m);
                        } else {
                            time = m.getAddTime();
                            ++j;
                            l = new ArrayList();
                            l.add(m);
                            array.put(j, l);
                        }
                    }
                    list.clear();
                    ArrayList result = new ArrayList();
                    for (int i = 0; i < array.size(); i++) {
                        l = array.valueAt(i);
                        result.add(l.get(0).getAddTime());
                        result.addAll(l);
                    }
                    h.post(() -> {
                        if (isFinishing() || isDestroyed()) {
                            return;
                        }
                        adapter.setData(result, page);
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    h.post(() -> working = false);
                }
            }
        });
    }

    public void selectChange(int num) {
        if (num <= 0) {
            binding.btnAdd.setEnabled(false);
            binding.btnAdd.setAlpha(0.5f);
            binding.btnAdd.setText(from == 1 ? "开始拼图（0张）" : "批量加水印（0张）");
        } else {
            binding.btnAdd.setEnabled(true);
            binding.btnAdd.setAlpha(1f);
            binding.btnAdd.setText(from == 1 ? "开始拼图（" + num + "张）" : "批量加水印（" + num + "张）");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }
}
